package com.apex.lottery.service.strategy.execution;

import cn.hutool.core.date.DateUtil;
import com.apex.lottery.common.utils.MailUtil;
import com.apex.lottery.dao.dataobject.WinningRecordDO;
import com.apex.lottery.service.enums.ActivityPrizeTiersEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.List;

import static com.apex.lottery.common.constant.Constants.NOTIFICATION_SUBJECT;

/**
 * @ClassName SendMailStrategy
 * @Description
 * @Author ZJX
 * @Date 2025/4/23 19:47
 * @Version 1.0
 **/
@Slf4j
@Component
public class SendMailStrategy implements TaskExecutionStrategy{
    @Autowired
    private MailUtil mailUtil;

    @Qualifier("asyncServiceExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public SendMailStrategy(@Qualifier("asyncServiceExecutor") ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
    }

    @Override
    public void execute(List<WinningRecordDO> winningRecordDOList) {
        threadPoolTaskExecutor.execute(() -> sendMail(winningRecordDOList));
    }

    private void sendMail(List<WinningRecordDO> winningRecordDOList) {
        // 发送邮件的逻辑
        if (CollectionUtils.isEmpty(winningRecordDOList)) {
            log.info("中奖列表为空，不用发邮件！");
            return;
        }

        winningRecordDOList
                        .forEach(winningRecordDO -> {
                            String context = "Hi，" + winningRecordDO.getWinnerName() + "。恭喜你在"
                                    + winningRecordDO.getActivityName() + "活动中获得"
                                    + ActivityPrizeTiersEnum.forName(winningRecordDO.getPrizeTier()).getMessage()
                                    + "：" + winningRecordDO.getPrizeName() + "。获奖时间为"
                                    + DateUtil.formatTime(winningRecordDO.getWinningTime()) + "，请尽快领取您的奖励！";
                            mailUtil.sendSampleMail(winningRecordDO.getWinnerEmail(),
                                    NOTIFICATION_SUBJECT, context);
                        });
    }
}
